package org.budo.druid;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.budo.druid.filter.stat.BudoMergeStatFilter;
import org.budo.druid.filter.wall.BudoWallFilterFactoryBean;
import org.budo.support.lang.util.ListUtil;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * @author lmw
 */
public class Druid {
    private static final Map<String, DataSource> _dataSourceMap = new ConcurrentHashMap<String, DataSource>();

    public static DataSource dataSource(String url) {
        try {
            if (_dataSourceMap.containsKey(url)) {
                return _dataSourceMap.get(url);
            }

            synchronized (Druid.class) {
                if (_dataSourceMap.containsKey(url)) {
                    return _dataSourceMap.get(url);
                }

                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setUrl(url);
                dataSource.setProxyFilters(ListUtil.toList(BudoWallFilterFactoryBean.budoWallFilter(), //
                        new BudoMergeStatFilter()));

                _dataSourceMap.put(url, dataSource);

                return dataSource;
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}